<?php

namespace Kangcg\Application\Validate\Rules;



use Kangcg\Application\Validate\Validator;

class Amount implements RuleInterface
{
    use RuleTrait;
    public $max = null;

    public $min = null;

    protected function afterRun(&$value, string $field, array $input, Validator $validator)
    {
        $pattern = "/^\d+(\.\d{1,2})?$/";
        if(!preg_match($pattern, $value)){
            return $validator->setError($this->getMessage($field));
        }

        $value = floatval($value);
        if($this->max !== null){
            $bool = $validator->getRuleInstall('max', $this->_rules, ['max' => $this->max])->run($value, $field, $input, $validator);
            if($bool === false){
                return false;
            }
        }

        if($this->min !== null){
            $bool = $validator->getRuleInstall('min', $this->_rules, ['min' => $this->max])->run($value, $field, $input, $validator);
            if($bool === false){
                return false;
            }
        }
    }

    public function extra($extra)
    {
        if(isset($extra['max']) || isset($extra['min'])){
            return $extra;
        }

        if(is_int($extra)){
            return [
                'max' => $extra,
            ];
        }

        return $extra;
    }
}
